package com.atguigu.controller;


import com.alibaba.fastjson.JSONObject;
import com.atguigu.constant.RedisConst;
import com.atguigu.entity.UserInfo;
import com.atguigu.result.RetVal;
import com.atguigu.service.UserInfoService;
import com.atguigu.util.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author linjiang
 * @since 2022-08-04
 */
@RestController
@RequestMapping("/user")
public class UserLoginController {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate redisTemplate;
    //1.登录的认证逻辑
    @PostMapping("login")
    public RetVal login(@RequestBody UserInfo uiUserInfo,HttpServletRequest request){
        //验证 账号 密码
      UserInfo userInfo=userInfoService.login(uiUserInfo);
      //生成一个token 返回给前端（cookie）
        if(userInfo!=null){
          Map<Object, Object> RestMap = new HashMap<>();
            String token = UUID.randomUUID().toString();
            RestMap.put("token",token);
            String nickName = userInfo.getNickName();
            RestMap.put("nickName",nickName);

            //将数据存入  redis
            String userKey= RedisConst.USER_LOGIN_KEY_PREFIX+token;
            JSONObject userJsonObject = new JSONObject();
            userJsonObject.put("userId",userInfo.getId());
            userJsonObject.put("loginIp", IpUtil.getIpAddress(request));
            redisTemplate.opsForValue().set(userKey,userJsonObject, RedisConst.USERKEY_TIMEOUT,TimeUnit.SECONDS);

            return RetVal.ok(RestMap);
        }else {
            return RetVal.fail("登陆失败,请重新登录");
        }

    }
    @GetMapping("logout")
    public RetVal logout(HttpServletRequest request) {

        String token = request.getHeader("token");

        String userKey=RedisConst.USER_LOGIN_KEY_PREFIX+token;
        redisTemplate.delete(userKey);
        return RetVal.ok();
    }

}

